package com.example.pcbcsmbackend.service;

import com.example.pcbcsmbackend.entity.User;
import com.example.pcbcsmbackend.repository.UserRepository;
import com.example.pcbcsmbackend.repository.AddressRepository;
import com.example.pcbcsmbackend.repository.OrderRepository;
import com.example.pcbcsmbackend.repository.OrderDetailRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private AddressRepository addressRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private OrderDetailRepository orderDetailRepository;

    // 用户注册
    public User register(String username, String password, String email, String phoneNumber) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (email != null && !email.isEmpty() && userRepository.existsByEmail(email)) {
            throw new RuntimeException("邮箱已被注册");
        }
        
        // 检查手机号是否已存在
        if (phoneNumber != null && !phoneNumber.isEmpty() && userRepository.existsByPhoneNumber(phoneNumber)) {
            throw new RuntimeException("手机号已被注册");
        }
        
        User user = new User(username, password, email, phoneNumber);
        return userRepository.save(user);
    }
    
    // 用户登录
    public User login(String username, String password) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            if (user.getPassword().equals(password) && user.getStatus() == 1) {
                // 更新最后登录时间
                user.setLastLogin(LocalDateTime.now());
                userRepository.save(user);
                return user;
            }
        }
        throw new RuntimeException("用户名或密码错误");
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public Optional<User> findById(Integer userId) {
        return userRepository.findById(userId);
    }

    public User updateUser(User user) {
        user.setUpdatedAt(LocalDateTime.now());
        return userRepository.save(user);
    }
    
    // 更新用户信息（管理员功能）
    public User updateUserInfo(Integer userId, String username, String email, String phoneNumber, Integer status) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 检查用户名是否已被其他用户使用
        if (username != null && !username.equals(user.getUsername()) && userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已被其他用户使用
        if (email != null && !email.isEmpty() && !email.equals(user.getEmail()) && userRepository.existsByEmail(email)) {
            throw new RuntimeException("邮箱已被注册");
        }
        
        // 检查手机号是否已被其他用户使用
        if (phoneNumber != null && !phoneNumber.isEmpty() && !phoneNumber.equals(user.getPhoneNumber()) && userRepository.existsByPhoneNumber(phoneNumber)) {
            throw new RuntimeException("手机号已被注册");
        }
        
        if (username != null) user.setUsername(username);
        if (email != null) user.setEmail(email);
        if (phoneNumber != null) user.setPhoneNumber(phoneNumber);
        if (status != null) user.setStatus(status);
        
        user.setUpdatedAt(LocalDateTime.now());
        return userRepository.save(user);
    }
    
    // 创建用户（管理员功能）
    public User createUser(String username, String password, String email, String phoneNumber, Integer status) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (email != null && !email.isEmpty() && userRepository.existsByEmail(email)) {
            throw new RuntimeException("邮箱已被注册");
        }
        
        // 检查手机号是否已存在
        if (phoneNumber != null && !phoneNumber.isEmpty() && userRepository.existsByPhoneNumber(phoneNumber)) {
            throw new RuntimeException("手机号已被注册");
        }
        
        User user = new User(username, password, email, phoneNumber);
        if (status != null) {
            user.setStatus(status);
        }
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        return userRepository.save(user);
    }
    
    // 删除用户（管理员功能）
    @Transactional
    public void deleteUser(Integer userId) {
        if (!userRepository.existsById(userId)) {
            throw new RuntimeException("用户不存在");
        }
        try {
            // 先删除用户的地址
            addressRepository.deleteByUserId(userId);
            
            // 删除用户的订单详情（通过订单ID）
            List<Integer> userOrderIds = orderRepository.findOrderIdsByUserId(userId);
            if (!userOrderIds.isEmpty()) {
                orderDetailRepository.deleteByOrder_OrderIdIn(userOrderIds);
            }
            
            // 删除用户的订单
            orderRepository.deleteByUserId(userId);
            
            // 最后删除用户
            userRepository.deleteById(userId);
        } catch (Exception e) {
            throw new RuntimeException("删除用户失败: " + e.getMessage());
        }
    }

    public void updateUserStatus(Integer userId, Integer status) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        user.setStatus(status);
        user.setUpdatedAt(LocalDateTime.now());
        userRepository.save(user);
    }
    
    @Transactional
    public void batchUpdateUserStatus(List<Integer> userIds, Integer status) {
        List<User> usersToUpdate = userRepository.findAllById(userIds);
        LocalDateTime now = LocalDateTime.now();
        for (User user : usersToUpdate) {
            user.setStatus(status);
            user.setUpdatedAt(now);
        }
        userRepository.saveAll(usersToUpdate);
    }
    
    @Transactional
    public void batchDeleteUsers(List<Integer> userIds) {
        try {
            for (Integer userId : userIds) {
                // 先删除用户的地址
                addressRepository.deleteByUserId(userId);
                
                // 删除用户的订单详情（通过订单ID）
                List<Integer> userOrderIds = orderRepository.findOrderIdsByUserId(userId);
                if (!userOrderIds.isEmpty()) {
                    orderDetailRepository.deleteByOrder_OrderIdIn(userOrderIds);
                }
                
                // 删除用户的订单
                orderRepository.deleteByUserId(userId);
            }
            
            // 最后批量删除用户
            userRepository.deleteAllById(userIds);
        } catch (Exception e) {
            throw new RuntimeException("批量删除用户失败: " + e.getMessage());
        }
    }
} 